var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sassMiddleware = require('node-sass-middleware');
var session = require("express-session");
var NedbStore = require('nedb-session-store')( session );
session = session({
    secret: "fas fas",
    resave: false,
    saveUninitialized: false,
    cookie: {
      path: '/',
      httpOnly: true,
      maxAge: 200 * 60 * 60 * 1000
    },
    store: new NedbStore({
      filename: 'path_to_nedb_persistence_file.db'
    })
  })
var iosession = require("express-socket.io-session")(session,{autoSave:true});
var ChatMsg = require("./routes/db/ChatMsg");

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

var server = require("http").Server(app);
var io = require("socket.io")(server);
// server.listen(3000);
io.use(iosession);

io.on("connection", function (socket) {
  // console.log("lian jie ----");
  // socket.on("req", function(data, cb) {
  //   cb();
  // })
  socket.on("say", data=>{

    let date = new Date();
   io.emit("back",{msg:data.msg,name:data.name,date});
   let u= new ChatMsg({
     msg:data.msg,
     createData: date,
     auther: data.name
   });
   u.save();
})
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(sassMiddleware({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: false, // true = .sass and false = .scss
  // sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('trust proxy', 1);
app.use(session);
app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', true);
    //告诉客户端可以接受请求的方式
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  next();
})
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = {app,server};
